#
# This file is a part of the open-eBackup project.
# This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
# If a copy of the MPL was not distributed with this file, You can obtain one at
# http://mozilla.org/MPL/2.0/.
#
# Copyright (c) [2024] Huawei Technologies Co.,Ltd.
#
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
# EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
# MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
#

from common.common import check_command_injection
from common.logger import Logger
from common.util.check_user_utils import check_os_user_raise_ex
from db2.comm.constant import DB2Type
from db2.comm.param_parse import Param
from db2.comm.db2_cmd import check_cluster_node
from db2.comm.const import Db2JsonConstant
from common.number_const import NumberConst

LOGGER = Logger().get_logger(filename="db2.log")


class QueryCluster:
    def __init__(self, pid, param: Param):
        self.pid = pid
        self.context = param
        self.instance = self.context.application
        self.name = self.instance.get("name")
        if self.name:
            if check_command_injection(self.name):
                raise Exception("Param of name(instance) invalid")
        LOGGER.info(f"query cluster")

    def query_cluster_ha(self):
        LOGGER.info(f"Begin to query cluster from  pid :{self.pid}")
        ret, params = check_cluster_node(self.name)
        if not ret:
            role = str(NumberConst.TWO)
            return self.message_struct(role)
        role = str(NumberConst.ONE)
        return self.message_struct(role)

    def message_struct(self, role: str):
        resource = dict()
        resource_type = []
        node = dict()
        resource[Db2JsonConstant.ID] = ""
        resource[Db2JsonConstant.TYPE] = DB2Type.TYPE
        resource[Db2JsonConstant.SUBTYPE] = DB2Type.DB2INSTANCE
        resource[Db2JsonConstant.NAME] = ""
        resource[Db2JsonConstant.ENDPOINT] = ""
        resource[Db2JsonConstant.NODES] = resource_type
        resource_type.append(node)
        node[Db2JsonConstant.EXTEND_INFO] = {"role": role}
        LOGGER.info(f"role for cluster :{role}, pid: {self.pid}.")
        return resource
